import React, { useState, useRef, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Product, ProductSpec } from './types/product';
import './ProductDetail.css';
import Layout from './Layout';

const ProductDetail = () => {
    const navigate = useNavigate();
    const [selectedSpecs, setSelectedSpecs] = useState<ProductSpec>({});
    const [selectedServices, setSelectedServices] = useState<string[]>([]);
    const [selectedAccessories, setSelectedAccessories] = useState<string[]>([]);
    const [selectedImage, setSelectedImage] = useState(0);
    const [magnifierPosition, setMagnifierPosition] = useState({ x: 0, y: 0 });
    const [showMagnifier, setShowMagnifier] = useState(false);
    const imageRef = useRef<HTMLImageElement>(null);
    const magnifierRef = useRef<HTMLDivElement>(null);

    // 模拟商品数据
    const product: Product = {
        id: '1',
        name: 'HUAWEI Mate 70 RS 非凡大师', 
        price: 11999,
        originalPrice: 12999,
        description: '双层OLED临境显示，高亮钛玄武架构，传奇星钻设计',
        specs: {
            colors: ['玄黑', '皓白', '瑞红'],
            storages: ['16GB+512GB', '16GB+1TB'],
            versions: ['标准版', '典藏版']
        },
        images: [
            'https://res2.vmallres.com/pimages/FssCdnProxy/vmall_product_uom/pmsSalesFile/428_428_D0C8A9A011D150F59C4108C3AF625E3C.png',
            'https://res2.vmallres.com/pimages/FssCdnProxy/vmall_product_uom/pmsSalesFile/428_428_9C184F1C0619FCBA06A38AB2B2A4417D.png',
            'https://res2.vmallres.com/pimages/FssCdnProxy/vmall_product_uom/pmsSalesFile/428_428_E1D92BB1734CBC59D67573D18C3C5558.png'
        ],
        features: [
            '双层OLED临境显示',
            '高亮钛玄武架构',
            '传奇星钻设计'
        ],
        parameters: {
            '电池容量': '5700mAh（典型值）',
            '后置摄像头': '5000万像素超聚光摄像头',
            '前置摄像头': '1300万像素超广角摄像头',
            '屏幕尺寸': '6.9英寸',
            '机身内存': '512GB/1TB'
        },
        services: [
            {
                id: '1',
                name: 'HUAWEI Care+（一年期）标准版',
                price: 899,
                description: '延长保修服务'
            },
            {
                id: '2',
                name: '延长服务宝（一年期）',
                price: 499,
                description: '延长保修服务'
            }
        ],
        accessories: [
            {
                id: '1',
                name: 'HUAWEI FreeBuds 6 悦彰耳机',
                price: 999,
                image: 'https://res2.vmallres.com/pimages/FssCdnProxy/vmall_product_uom/pmsSalesFile/428_428_D63B5EE642F9D4029EBE832E00A06464.png',
                description: '悦彰耳机'
            },
            {
                id: '2',
                name: 'HUAWEI WATCH GT 5 Pro（46mm）',
                price: 2188,
                image: 'https://res2.vmallres.com/pimages/uomcdn/CN/pms/202409/gbom/6942103132216/428_428_9BAD3BCC24D62F134982BB23E027583Bmp.png',
                description: '手表'
            }
        ]
    };

    const handleSpecChange = (type: keyof ProductSpec, value: string) => {
        setSelectedSpecs(prev => ({
            ...prev,
            [type]: value
        }));
    };

    const handleServiceChange = (serviceId: string) => {
        setSelectedServices(prev =>
            prev.includes(serviceId)
                ? prev.filter(id => id !== serviceId)
                : [...prev, serviceId]
        );
    };

    const handleAccessoryChange = (accessoryId: string) => {
        setSelectedAccessories(prev =>
            prev.includes(accessoryId)
                ? prev.filter(id => id !== accessoryId)
                : [...prev, accessoryId]
        );
    };

    const calculateTotal = useMemo(() => {
        let total = product.price;

        // 添加服务费用
        if (selectedServices && selectedServices.length > 0) {
            selectedServices.forEach(serviceId => {
                const service = product.services.find(s => s.id === serviceId);
                if (service) {
                    total += service.price;
                }
            });
        }

        // 添加配件费用
        if (selectedAccessories && selectedAccessories.length > 0) {
            selectedAccessories.forEach(accessoryId => {
                const accessory = product.accessories.find(a => a.id === accessoryId);
                if (accessory) {
                    total += accessory.price;
                }
            });
        }

        return total;
    }, [product.price, selectedServices, selectedAccessories, product.services, product.accessories]);

    const handleAddToCart = () => {
        const cartItem = {
            ...product,
            quantity: 1,
            selectedSpecs,
            selectedServices,
            selectedAccessories,
        };

        // 将商品添加到购物车
        const cartItems = JSON.parse(localStorage.getItem('cartItems') || '[]');
        cartItems.push(cartItem);
        localStorage.setItem('cartItems', JSON.stringify(cartItems));

        if (!selectedSpecs.color) {
            alert('请选择颜色');
            return;
        } else if (!selectedSpecs.storage) {
            alert('请选择存储容量');
            return;
        } else {
            navigate('/cart');
        }
        // 跳转到购物车页面

    };

    const handleBuyNow = () => {
        const orderItem = {
            ...product,
            quantity: 1,
            selectedSpecs,
            selectedServices,
            selectedAccessories
        };

        // 将商品添加到订单
        localStorage.setItem('currentOrder', JSON.stringify([orderItem]));
        sessionStorage.setItem('orders', JSON.stringify([orderItem]));

        if (!selectedSpecs.color) {
            alert('请选择颜色');
            return;
        } else if (!selectedSpecs.storage) {
            alert('请选择存储容量');
            return;
        } else {
            navigate('/order-confirm');
        }
        // 跳转到订单确认页面

    };

    const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
        if (!imageRef.current || !magnifierRef.current) return;

        const { left, top, width, height } = imageRef.current.getBoundingClientRect();
        const x = e.clientX - left;
        const y = e.clientY - top;

        // 计算放大镜位置
        const magnifierSize = 200;
        const magnifierX = Math.min(Math.max(x - magnifierSize / 2, 0), width - magnifierSize);
        const magnifierY = Math.min(Math.max(y - magnifierSize / 2, 0), height - magnifierSize);

        // 计算放大倍数
        const scaleX = 2;
        const scaleY = 2;

        setMagnifierPosition({
            x: -x * scaleX + magnifierSize / 2,
            y: -y * scaleY + magnifierSize / 2
        });
    };
    return (
        <Layout>
            <div className="product-detail">
                <div className="product-header">
                    <div
                        className="product-gallery"
                        onMouseEnter={() => setShowMagnifier(true)}
                        onMouseLeave={() => setShowMagnifier(false)}
                        onMouseMove={handleMouseMove}
                    >
                        <img
                            ref={imageRef}
                            src={product.images[selectedImage]}
                            alt={product.name}
                            className="main-image"
                        />
                        {showMagnifier && (
                            <div
                                ref={magnifierRef}
                                className="magnifier"
                                style={{
                                    backgroundImage: `url(${product.images[selectedImage]})`,
                                    backgroundPosition: `${magnifierPosition.x}px ${magnifierPosition.y}px`,
                                    backgroundSize: `${200 * 5}px ${200 * 5}px`
                                }}
                            />
                        )}
                        <div className="thumbnail-list">
                            {product.images.map((image, index) => (
                                <img
                                    key={index}
                                    src={image}
                                    alt={`${product.name} ${index + 1}`}
                                    className={selectedImage === index ? 'active' : ''}
                                    onClick={() => setSelectedImage(index)}
                                />
                            ))}
                        </div>
                    </div>
                    <div className="product-info">
                        <h1>{product.name}</h1>
                        <p className="description">{product.description}</p>

                        <div className="price-section">
                            <span className="price">¥{product.price}</span>
                            {product.originalPrice && (
                                <span className="original-price">¥{product.originalPrice}</span>
                            )}
                        </div>

                        <div className="specs-section">
                            <h3>颜色</h3>
                            <div className="spec-options">
                                {product.specs.colors.map(color => (
                                    <button
                                        key={color}
                                        className={`spec-btn ${selectedSpecs.color === color ? 'selected' : ''}`}
                                        onClick={() => handleSpecChange('color', color)}
                                    >
                                        {color}
                                    </button>
                                ))}
                            </div>

                            <h3>存储容量</h3>
                            <div className="spec-options">
                                {product.specs.storages.map(storage => (
                                    <button
                                        key={storage}
                                        className={`spec-btn ${selectedSpecs.storage === storage ? 'selected' : ''}`}
                                        onClick={() => handleSpecChange('storage', storage)}
                                    >
                                        {storage}
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div className="services-section">
                            <h3>保障服务</h3>
                            {product.services.map(service => (
                                <div key={service.id} className="service-item">
                                    <label>
                                        <input
                                            type="checkbox"
                                            checked={selectedServices.includes(service.id)}
                                            onChange={() => handleServiceChange(service.id)}
                                        />
                                        {service.name}
                                    </label>
                                    <span className="service-price">¥{service.price}</span>
                                </div>
                            ))}
                        </div>

                        <div className="accessories-section">
                            <h3>配件</h3>
                            {product.accessories.map(accessory => (
                                <div key={accessory.id} className="accessory-item">
                                    <label>
                                        <input
                                            type="checkbox"
                                            checked={selectedAccessories.includes(accessory.id)}
                                            onChange={() => handleAccessoryChange(accessory.id)}
                                        />
                                        <img src={accessory.image} alt={accessory.name} />
                                        <div className="accessory-info">
                                            <span className="accessory-name">{accessory.name}</span>
                                            <span className="accessory-price">¥{accessory.price}</span>
                                        </div>
                                    </label>
                                </div>
                            ))}
                        </div>

                        <div className="total-section">
                            <div className="total-price">
                                总计：¥{calculateTotal}
                            </div>
                            <div className="action-buttons">
                                <button className="add-to-cart" onClick={handleAddToCart}>
                                    加入购物车
                                </button>
                                <button className="buy-now" onClick={handleBuyNow}>
                                    立即购买
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="product-details">
                    <h2>产品参数</h2>
                    <div className="parameters">
                        {Object.entries(product.parameters).map(([key, value]) => (
                            <div key={key} className="parameter-item">
                                <span className="parameter-key">{key}</span>
                                <span className="parameter-value">{value}</span>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </Layout>
    );
};

export default ProductDetail; 